package Lirmm.VSM;
import Jama.*;

public class CosineSimilarity

{
	

	public double [][] CosineSimilarityMeasure(double [][]q,double [][]d)
	
	{
		
		
		Matrix tempQ, tempD, temp;
		double resultQ,  resultD, mult, sum=0, cosineT;
		
		Matrix QM= new Matrix (q);
		Matrix DM= new Matrix(d);
		
		QM = QM.transpose();
		DM = DM.transpose();
		
		//QM.print(1,11);
		
		double [][] CosineSimilarityMatrix= new double[QM.getRowDimension()][DM.getRowDimension()];
			
		final int r=QM.getColumnDimension();
		 int [] c= new int [r];
		
		for (int y=0;y<r;y++)
			c[y]=y;
			
			
		
		for(int i=0;i<QM.getRowDimension();i++) 
		{
			
			 
			for (int j=0;j<DM.getRowDimension();j++)
			{
				CosineSimilarityMatrix[i][j]=0.0;
			}
			
		}
		 
		//System.err.println(" CosineSimilarityMatrix r : c "+QM.getRowDimension() +": "+ DM.getRowDimension());
		
		

		for(int i=0;i<QM.getRowDimension();i++) 
		{
						
			tempQ=QM.getMatrix(i, i, c);
			//tempQ.print(1, 11);
			resultQ=tempQ.normF();    // normF is a sqrt of sum of squares of all elements.
		  
						
			for (int j=0;j<DM.getRowDimension();j++)
			{
				
				tempD=DM.getMatrix(j, j, c);
				resultD=tempD.normF();      // normF is a sqrt of sum of squares of all elements.
				
				mult=resultD * resultQ; //  Denominator
				sum=0;
				for (int yy=0;yy<r;yy++ )
				{
					
					sum=sum+(tempD.get(0, yy)*tempQ.get(0, yy)); // numerator
				
				}
				
				cosineT= sum/mult;
				CosineSimilarityMatrix[i][j]=cosineT;
								
				
			}
		}
	
			
		//Validation(q,d,CosineSimilarityMatrix);
		
		return CosineSimilarityMatrix;
	}
	
	 public void Validation(double [][]q,double [][]d, double [][]s)
	  {
		  	
			
		
			
			Matrix temp2 = new Matrix (q);
			temp2.print(temp2.getRowDimension(),temp2.getColumnDimension());
			System.out.println("=============== dfidf_Query =============");
			
			Matrix temp3 =   new Matrix (d);
			temp3.print(temp3.getRowDimension(),temp3.getColumnDimension());
			System.out.println("=============== dfidf_Document =============");
			
			Matrix temp4  = new Matrix (s);
			temp4.print(temp4.getRowDimension(),temp4.getColumnDimension());
			System.out.println("=============== cosine similarity matrix =============");
		
			
			
			 
			
		  
	  }
}
